package com.fjp.heartguard.viewmodel

import androidx.lifecycle.MutableLiveData
import com.fjp.heartguard.app.base.HTBaseViewModel
import com.fjp.heartguard.app.data.bean.OlderInfo
import com.fjp.heartguard.app.data.bean.SaveQuestionResult
import com.fjp.heartguard.app.network.HttpRequestCoroutine
import me.hgj.jetpackmvvm.ext.request
import me.hgj.jetpackmvvm.ext.requestNoCheck
import me.hgj.jetpackmvvm.state.ResultState
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File

/**
 *Author:Mr'x
 *Time:2025/1/19
 *Description:
 */
class ReportLocalViewModel : HTBaseViewModel() {
    var updateFailed = MutableLiveData<Boolean>()
    var updateSuccess = MutableLiveData<ResultState<SaveQuestionResult>>()

    fun update(olderInfo: OlderInfo) {
        val file = File(olderInfo.signature)

        if (file.exists()) {
            val index = file.name.lastIndexOf(".");
            var fileType = file.name.substring(index + 1)
            if (fileType == "jpg") {
                fileType = "jpeg"
            }

            // 创建图片的Part
            val reqFile = RequestBody.create(MediaType.parse("image/" + fileType), file)
            val body = MultipartBody.Part.createFormData("file", file.name, reqFile)
            requestNoCheck({ HttpRequestCoroutine.uploadImg(body) }, {
                //请求成功 自己拿到数据做业务需求操作
                if (it.status == "success") {
                    olderInfo.signature = it.data
                    if (olderInfo.audio_file.length != 0 && File(olderInfo.audio_file).exists()) {
                        updateAudio(olderInfo)
                    } else {
                        saveQuestionnaireInfo(olderInfo)
                    }
                }
            }, {
                updateFailed.value = true
            }, false)
        }
    }

    fun saveQuestionnaireInfo(olderInfo: OlderInfo) {
        request({
            HttpRequestCoroutine.saveQuestionnaireInfo(olderInfo)
        }, updateSuccess, false)
    }

    fun updateAudio(olderInfo: OlderInfo) {
        val file = File(olderInfo.audio_file)

        val reqFile = RequestBody.create(MediaType.parse("audio"), file)
        val body = MultipartBody.Part.createFormData("file", file.name, reqFile)
        requestNoCheck({ HttpRequestCoroutine.uploadImg(body) }, {
            //请求成功 自己拿到数据做业务需求操作
            if (it.status == "success") {
                olderInfo.audio_file = it.data
                saveQuestionnaireInfo(olderInfo)
            }
        }, {
            updateFailed.value = true
        }, false)
    }


}